/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.raflik.queryxml.ui.tasks;

import pl.raflik.queryxml.ui.*;
import java.awt.EventQueue;

/**
 *
 * @author raflik
 */
public abstract class AsyncOperationThread<Input, Output> implements Runnable {

    private UITransfer<Input, Output> transfer;
    private Output output;

    public AsyncOperationThread(UITransfer<Input, Output> transfer) {
        this.transfer = transfer;

    }

    protected abstract Output performOperation(Input input);

    public final void run() {
        if (!EventQueue.isDispatchThread()) {
            // processing thread
            // do the work
            final Input input = transfer.readUI();
            output = performOperation(input);

            // go to UI thread
            EventQueue.invokeLater(this);
        } else {
            // UI thread
            transfer.writeUI(output);
        }
    }
}
